#!/bin/sh

VERSION="3.0.3"
VIRTUALENV="https://raw.github.com/pypa/virtualenv/master/virtualenv.py"

set -e

download_url() {
    if [ -x "/usr/bin/curl" ] ; then
        /usr/bin/curl -# -O $1
    elif [ -x "/usr/bin/wget" ] ; then
        /usr/bin/wget -q $1
    else
        echo "Unable to install Meteor: can't find wget or curl in /usr/bin."
        exit 1
    fi
}

TARGET="/usr/local/pydap"
PARENT="/usr/local"

echo "Installing Pydap to $TARGET"
mkdir -p ${TARGET}

# create virtualenv
cd ${TARGET}
download_url ${VIRTUALENV}
python ${TARGET}/virtualenv.py ${TARGET}/env
. ${TARGET}/env/bin/activate

# install packages
pip install "Pydap==${VERSION}"
pip install pydap.handlers.netcdf
pip install uWSGI

# create pydap run script
cd ${TARGET}
paster create -t pydap server
cat > ${TARGET}/env/bin/pydap << EOF
#!/bin/sh

exec ${TARGET}/env/bin/uwsgi \
    --http-socket 0.0.0.0:8001 \
    -H ${TARGET}/env \
    --master --processes 4 \
    --paste config:${TARGET}/server/server.ini

EOF
chmod +x ${TARGET}/env/bin/pydap

# add to $PATH
mkdir -p "$PARENT/bin"
ln -sf "$TARGET/env/bin/pydap" "$PARENT/bin/pydap"

cat << EOF

Pydap installed! To get started put your data in:

  ${TARGET}/server/data

And run:

  $ pydap 

Now point your browser to:

  http://localhost:8001/

Or see the docs at:

  http://pydap.org/

EOF
